package com.s7.ui;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresPermission;

import com.s7.ui.helper.ProcessHelper;
import com.s7.ui.helper.ServiceHelper;
import com.s7.ui.util.MMKVHelper;

import java.util.Stack;

import static android.Manifest.permission.KILL_BACKGROUND_PROCESSES;

/**
 * SUI全局设置
 */
public class SUI implements Application.ActivityLifecycleCallbacks {

    private static SUI sInstance;

    // Activity 管理栈
    private Stack<Activity> mActivityStack = new Stack<>();

    // 全局上下文对象
    private static Context sContext;

    /**
     * 获取单例
     * @return
     */
    @MainThread
    public static SUI getInstance() {
        if (sInstance == null) {
            throw new IllegalAccessError("the SUI is not initialized; " +
                    "please call SUI.init(Application) in your application.");
        }
        return sInstance;
    }

    private SUI() {
    }

    /**
     * 初始化 SUI
     * @param application
     */
    public static void init(@NonNull Application application) {
        if (sInstance == null) {
            sInstance = new SUI();
            sContext = application.getApplicationContext();
            // 注册activity的生命回调
            application.registerActivityLifecycleCallbacks(sInstance);
            // 初始化MMKV
            MMKVHelper.init(application);
        }
    }

    /**
     * 获取全局上下文
     * @return
     */
    public static Context getContext() {
        testInitialize();
        return sContext;
    }

    private static void testInitialize() {
        if (sContext == null) {
            throw new ExceptionInInitializerError("请先在全局Application中调用 SUI.init(Application) 初始化！");
        }
    }

    /**
     * 将activity存入栈中
     * @param activity
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        mActivityStack.add(activity);
    }

    /**
     * 将activity从栈中移除
     * @param activity
     */
    @Override
    public void onActivityDestroyed(Activity activity) {
        mActivityStack.remove(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    /**
     * 获取倒数第二个Activity
     * @param current 最后一个Activity
     * @return
     */
    @Nullable
    public Activity getPenultimateActivity(Activity current) {
        Activity activity = null;
        try {
            if (mActivityStack.size() > 1) {
                // 获取倒数第二个Activity
                activity = mActivityStack.get(mActivityStack.size() - 2);
                // 判断两个activity是不是同一个
                if (current.equals(activity)) {
                    // 获取最后一个activity的指数
                    int index = mActivityStack.indexOf(current);
                    if (index > 0) {
                        // if memory leaks or the last activity is being finished
                        activity = mActivityStack.get(index - 1);
                    } else if (mActivityStack.size() == 2) {
                        // 如果屏幕方向改变，堆栈中可能有错误序列
                        activity = mActivityStack.lastElement();
                    }
                }
            }
        } catch (Exception ignored) {
        }
        return activity;
    }

    /**
     * 是否有上一级（栈中的activity数量大于1）
     * @return
     */
    public boolean canSwipeBack() {
        return mActivityStack.size() > 1;
    }

    /**
     * 结束所有Activity
     */
    public void finishAll() {
        if (mActivityStack != null) {
            for (int i = 0, size = mActivityStack.size(); i < size; i++) {
                Activity activity = mActivityStack.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
//                        Logger.d("[FinishActivity]:" + StringUtils.getName(activity));
                        activity.finish();
                    }
                }
            }
            mActivityStack.clear();
        }
    }

    /**
     * 退出应用程序
     */
    @RequiresPermission(KILL_BACKGROUND_PROCESSES)
    public void exitApp() {
        if (mActivityStack != null) {
            finishAll();
        }
        // 关闭所有服务
        ServiceHelper.stopAllRunningService(getContext());
        // 杀死进程
        ProcessHelper.killBackgroundProcesses(getContext().getPackageName());
        System.exit(0);
    }
}
